package base

import (
	"strconv"

	"github.com/go-redis/redis"
	log "github.com/sirupsen/logrus"
)

//Employee 员工
type Employee struct {
	redisCli *redis.Client
	hkey     string
	hkey2    string
}

var emplCache *Employee

//GetEmployeeCache 获取员工
func GetEmployeeCache() (e *Employee) {
	if emplCache == nil {
		emplCache = &Employee{
			redisCli: RedisClients[0],
			hkey:     "employee",
			hkey2:    "emplOrgan",
		}
	}
	return emplCache
}

//Build 构建
func (e *Employee) Build() error {
	log.Info("开始构建员工")
	sql := "select id,SysUserName,OrganID from T_SysUser"
	rows, err := DB.Raw(sql).Rows()
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var name string
		var organID int
		err := rows.Scan(&id, &name, &organID)
		if err != nil {
			return err
		}
		if err := e.addData(id, name, organID); err != nil {
			return err
		}
	}
	log.Info("构建员工完成")
	return nil
}
func (e *Employee) addData(id int, name string, organID int) error {
	if err := e.redisCli.HSet(e.hkey, strconv.Itoa(id), name).Err(); err != nil {
		return err
	}
	if err := e.redisCli.HSet(e.hkey2, strconv.Itoa(id), organID).Err(); err != nil {
		return err
	}
	return nil
}

//CacheUser 缓存员工
func CacheUser(id int, name string, organID int) error {
	return GetEmployeeCache().addData(id, name, organID)
}

//GetNameByID 根据ID获取Name
func (e *Employee) GetNameByID(id int) (string, error) {
	name, err := e.redisCli.HGet(e.hkey, strconv.Itoa(id)).Result()
	if err != nil {
		return "", err
	}
	return name, nil
}

//GetDeptIDByID 根据ID获取部门ID
func (e *Employee) GetDeptIDByID(id int) (int, int, error) {
	organIDStr, err := e.redisCli.HGet(e.hkey2, strconv.Itoa(id)).Result()
	if err != nil {
		return 0, 0, err
	}
	oID, err := strconv.Atoi(organIDStr)
	if err != nil {
		return 0, 0, err
	}
	opid, err := GetDepartmentCache().GetPOrgIdByID(oID)
	if err != nil {
		return 0, 0, err
	}
	return oID, opid, nil
}

//GetDeptNameByID 根据ID获取部门Name
func (e *Employee) GetDeptNameByID(id int) (string, error) {
	organIDStr, err := e.redisCli.HGet(e.hkey2, strconv.Itoa(id)).Result()
	if err != nil {
		return "", err
	}
	oID, err := strconv.Atoi(organIDStr)
	if err != nil {
		return "", err
	}
	name, err := GetDepartmentCache().GetNameByID(oID)
	if err != nil {
		return "", err
	}
	return name, nil
}
